

const path = require('path');
const fs = require('fs');

/**
 * 检查文件夹路径是否存在，如果不存在则创建文件夹
 */
function mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
}

/**
 * 生成文件夹名称
 */
function getUploadDirName() {
    const date = new Date();
    let month = Number.parseInt(date.getMonth()) + 1;
    month = month.toString().length > 1 ? month : `0${month}`;
    const dir = `${date.getFullYear()}${month}${date.getDate()}`;
    return dir;
}

/**
 * 生成文件名称
 */
function getUploadFileName(ext) {
    return `${Date.now()}${Number.parseInt(Math.random() * 10000)}.${ext}`;
}

module.exports = function (file, src) {
    src = path.normalize(src);
    console.log(file,1111)
    let ext = file.mimetype.split('/')[1];
    let dirName = getUploadDirName();
    let fileName = getUploadFileName(ext);
    src = path.join(src, dirName);
    console.log(src)
    mkdirsSync(src);

    src = path.join(src, fileName);
    const reader = fs.createReadStream(file.path);
    const stream = fs.createWriteStream(src);
    reader.pipe(stream);

    return src;
};